﻿namespace LogManager.Gui.Views
{
    using LogManager.Gui.Helpers;
    using LogManager.Gui.UI.Helpers;
    using LogManager.Gui.ViewModels;
    using System.Collections.Specialized;
    using System.ComponentModel;
    using System.Windows;

    /// <summary>
    /// Interaction logic for MainView.xaml
    /// </summary>
    public partial class MainView : Window, IMainView
    {
        public IMainViewModel ViewModel
        {
            get { return this.GetViewModelFromDataContext<IMainViewModel>(); }
            set { this.DataContext = value; }
        }

        public MainView()
        {
            InitializeComponent();
            ((INotifyCollectionChanged)TreeView1.Items).CollectionChanged += TreeView1Items_CollectionChanged;
        }

        private void TreeView1Items_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (TreeView1.Items.IsEmpty)
            {
                pageTransitionControl.ShowPage(null);
            }
        }

        public bool ExpandAndSelectItem(object itemToSelect)
        {
            var item = TreeViewHelpers.GetTreeViewItem(this.TreeView1, itemToSelect);
            if (item != null)
            {
                item.IsSelected = true;
                item.BringIntoView();
                return true; ;
            }
            return false;
        }

        private void TreeView1Item_selected(System.Object sender, System.Windows.RoutedEventArgs e)
        {
            var selectedModel = (IViewModel)TreeView1.SelectedValue;
            pageTransitionControl.ShowPage(selectedModel.View);
        }

        private void SettingsItem_Click(object sender, RoutedEventArgs e)
        {
            pageTransitionControl.ShowPage(ViewModel.SettingsViewModel.View);
        }

        private void CheckAllItem_click(object sender, RoutedEventArgs e)
        {
            pageTransitionControl.ShowPage(ViewModel.CheckLocationsViewModel.View);
        }

        private void ExecuteMoveLogsItem_Click(object sender, RoutedEventArgs e)
        {
            pageTransitionControl.ShowPage(ViewModel.ExecuteArchivingViewModel.View);
        }

        private void TreeView1Item_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs args)
        {
            var selectedModel = (IViewModel)TreeView1.SelectedValue;

            if (selectedModel != null && pageTransitionControl.CurrentPage != selectedModel.View)
            {
                pageTransitionControl.ShowPage(selectedModel.View);
            }
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            base.OnClosing(e);
            this.ViewModel.OnWindowClosing(e);
        }
    }
}
